<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="名称" prop="equipName">
        <el-input
          v-model="queryParams.equipName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="rtsp 链接" prop="equipRtspurl">
        <el-input
          v-model="queryParams.equipRtspurl"
          placeholder="请输入设备的 rtsp 播放链接"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拉流地址" prop="equipPullurl">
        <el-input
          v-model="queryParams.equipPullurl"
          placeholder="请输入拉流地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="描述" prop="equipDes">
        <el-input
          v-model="queryParams.equipDes"
          placeholder="请输入描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="onlineTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.onlineTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择上线 离线时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:mqtt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:mqtt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:mqtt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:mqtt:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-user"
          size="mini"
          @click="feifei"
          >聊天机器人</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mqttList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备ID" align="center" prop="equipId" />
      <el-table-column label="名称" align="center" prop="equipName" />
      <el-table-column label="rtsp 链接" align="center" prop="equipRtspurl" />
      <el-table-column label="拉流地址" align="center" prop="equipPullurl" />
      <!-- <el-table-column label="类型" align="center" prop="equipType" /> -->
       <el-table-column label="类型" align="center">
        <template slot-scope="scope">{{
          scope.row.equipType == "1"
            ? "移动设备"
            : scope.row.equipType == "2"
            ? "视频设备"
            : "其他"
        }}</template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="equipDes" />
      <el-table-column label="设备状态" align="center" prop="equipStatus" />
      <el-table-column label="设备码" align="center">
        <!-- 图片的显示 -->
        <template slot-scope="scope">
          <div @click="qrCode(scope.row.equipId)">
            <vue-qr
              v-if="scope.row.equipId != null"
              :logoSrc="logoUrl"
              :text="scope.row.equipId"
              :size="50"
              :logoScale="0.3"
              :margin="0"
            ></vue-qr>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="上线离线时间" align="center" prop="onlineTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.onlineTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mqtt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:mqtt:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-mobile-phone"
            @click="handleMQTT(scope.row)"
            >MQTT</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="equipName">
          <el-input v-model="form.equipName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="rtsp 链接" prop="equipRtspurl">
          <el-input v-model="form.equipRtspurl" placeholder="请输入设备的 rtsp 播放链接" />
        </el-form-item>
        <el-form-item label="拉流地址" prop="equipPullurl">
          <el-input v-model="form.equipPullurl" placeholder="请输入拉流地址  用来造ws" />
        </el-form-item>
        <el-form-item label="描述" prop="equipDes">
          <el-input v-model="form.equipDes" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="上线离线时间" prop="onlineTime">
          <el-date-picker clearable size="small"
            v-model="form.onlineTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择上线 离线时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


   <el-dialog
      :visible.sync="visible"
      width="460px"
      append-to-body
      style="text-align: center"
    >
      <div slot="title" style="font-size: 24px; font-weight: 700">
        <span>二维码</span>
        <p>{{qrimgurl}}</p>
        
      </div>
      <qrshoe :imgurl="qrimgurl"></qrshoe>
    </el-dialog>


    <!-- MQTT dialgo -->
    <el-dialog
      :visible.sync="visibleMQTT"
      width="620px"
      append-to-body
      :title="subscription.topic"
      style="text-align: center"
      @close="handleCancle"
    >
      <ul class="msgs" ref="box">
        <template v-for="(item, index) in list">
          <!-- 左边：别人问 -->
          <li class="msg-l" v-if="!item.isME" :key="index">
            <div class="msg-box">
              <div class="title">{{ item.name }}</div>
              <p>{{ item.content }}</p>
            </div>
            <small>{{ item.time }}</small>
          </li>
          <!-- 右边：我回复 -->
          <li class="msg-r" v-else :key="index">
            <div class="msg-box">
              <div class="title">{{ item.name }}</div>
              <p>{{ item.content }}</p>
            </div>
            <small>{{ item.time }}</small>
          </li>
        </template>
      </ul>
      <div class="send-msg">
        <textarea @keyup.enter="sendMsg" v-model="val"></textarea>
        <i class="el-icon-position" @click="sendMsg"></i>
      </div>
    </el-dialog>


    <!-- //聊天机器人 -->
    <el-dialog
      :visible.sync="robotvisible"
      width="620px"
      append-to-body
      style="text-align: center"
    >
      <div slot="title" style="font-size: 24px; font-weight: 700">
        <span>聊天机器人</span>
        
      </div>
      <robot :showstate="robotvisible"></robot>
    </el-dialog>
    
  </div>
</template>

<script>
import { listMqtt, getMqtt, delMqtt, addMqtt, updateMqtt } from "@/views/mqttList/mqtt";
import vueQr from "vue-qr/src/packages/vue-qr.vue";
import qrshoe from "@/components/QrcodeShow";
import mqtt from "mqtt";
import robot from "@/views/mqttList/Robot";

export default {
  
  components: {
    vueQr,qrshoe,robot
  },
  name: "Mqtt",
  data() {
    return {

      //聊天机器人
      robotvisible: false,
      // MQTT 连接选项
      connection: {
        host: "119.23.211.181",
        port: 8083,
        endpoint: "/mqtt",
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // 认证信息
        clientId: "pc" + this.uuid2(16, 16), //客户端ID 只有在硬件设备上 才正式使用 切唯一， 其他软件上用名称+随机UUID 代替 模拟一个设备
        username: "admin",
        password: "public",
      },
      subscription: {
        //订阅  点击后 会改成设备码
        topic: "hangge",
        qos: 0,
      },
      publish: {
        //发表  点击后 会改成设备码
        topic: "hangge",
        qos: 0,
        payload: '{ "msg": "Hello, I am browser." }',
      },
      receiveNews: "",
      client: {
        connected: false,
      },
      subscribeSuccess: false,
      //以上是MQTT 連接
      visibleMQTT: false,
      val: "",
      list: [
        {
          name: "王二小",
          content: "你今天吃了吗？老铁",
          time: "2020-09-22 18:33:11",
          isME: 0,
        },
        {
          name: "三蹦子",
          content: "还没吃，还没吃，还没吃还没吃，还没吃",
          time: "2020-09-22 18:33:11",
          isME: 1,
        },
      ],
      //MQTT dialog

      visible: false,
      logoUrl: require("@/assets/3hlogo1.png"),
      qrimgurl: "",

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      mqttList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipName: null,
        equipRtspurl: null,
        equipPullurl: null,
        equipType: null,
        equipDes: null,
        equipStatus: null,
        onlineTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listMqtt(this.queryParams).then(response => {
        this.mqttList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipId: null,
        equipName: null,
        equipRtspurl: null,
        equipPullurl: null,
        equipType: null,
        equipDes: null,
        equipStatus: "0",
        createTime: null,
        onlineTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipId = row.equipId || this.ids
      getMqtt(equipId).then(response => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.equipId != null) {
            updateMqtt(this.form).then(response => {
               this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMqtt(this.form).then(response => {
               this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipIds = row.equipId || this.ids;
      this.$confirm('是否确认删除设备信息编号为"' + equipIds + '"的数据项？').then(function() {
        return delMqtt(equipIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/mqtt/export', {
        ...this.queryParams
      }, `mqtt_${new Date().getTime()}.xlsx`)
    },

    /** mqtt按钮操作 */
    handleMQTT(row) {
      const equipIds = row.equipId || this.ids;

      this.visibleMQTT = true;
      console.log(this.connection.clientId);

      this.subscription.topic = equipIds;
      this.publish.topic = equipIds;

      this.list = [];
      this.createConnection();
    },

    qrCode(row) {
      this.qrimgurl = row;
      this.visible = true;
    },

    handleCancle() {
      this.visibleMQTT = false;
       this.doUnSubscribe();
      this.destroyConnection();
    },
// 创建MQTT连接
    createConnection() {
      // 连接字符串, 通过协议指定使用的连接方式
      // ws 未加密 WebSocket 连接
      // wss 加密 WebSocket 连接
      // mqtt 未加密 TCP 连接
      // mqtts 加密 TCP 连接
      // wxs 微信小程序连接
      // alis 支付宝小程序连接
      const { host, port, endpoint, ...options } = this.connection;
      // const connectUrl = `mqtt://${host}:1883`
      const connectUrl = `ws://${host}:${port}${endpoint}`;
      try {
        this.client = mqtt.connect(connectUrl, options);
      } catch (error) {
        console.log("mqtt.connect error", error);
      }
      // mqtt连接
      this.client.on("connect", () => {
        console.log("Connection succeeded!");
      });
      // 链接异常处理
      this.client.on("error", (error) => {
        console.log("Connection failed", error);
      });
      // 断开发起重连
      // this.client.on('reconnect', (error) => {
      //   console.log('正在重连...', error)
      // })
      // 接收消息处理
      this.client.on("message", (topic, message) => {
        // this.receiveNews = this.receiveNews.concat(message); //历史记录
        console.log(` ${topic} == ${message}`);

        let msgobj = {
          name: "",
          msg: "",
        };
        try {
          msgobj = JSON.parse(message); //将字符串转换成json对象
        } catch (error) {
          msgobj.msg = message;
        }

        console.log(msgobj.name);
        let obj = {
          name: msgobj.name,
          content: msgobj.msg ? msgobj.msg : message,
          time: this.getNowTime("YYYY-mm-dd HH:MM", new Date()),
          isME: msgobj.name == "me" ? 1 : 0,
        };
        this.list.push(obj);
        this.scrollToBottom();
      });

      //消息订阅
      const { topic, qos } = this.subscription;
      this.client.subscribe(topic, qos, (error) => {
        if (!error) {
          console.log("订阅成功");
        } else {
          console.log("订阅失败");
          this.$message.error("连接失败！");
        }
      });
    },
    // 创建连接
    
    //取消订阅
     doUnSubscribe() {
       const { topic } = this.subscription
       this.client.unsubscribe(topic, error => {
         if (error) {
               console.log('Unsubscribe error', error)
             }
         })
     },
    
    //断开连接
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end();
          this.client = {
            connected: false,
          };
          console.log("Successfully disconnected!");
        } catch (error) {
          console.log("Disconnect failed", error.toString());
        }
      }
    },

    //
    sendMsg() {
      if (!this.val) {
        alert("发送内容不能为空~");
        return false;
      }
      // let now = this.getNowTime("YYYY-mm-dd HH:MM", new Date());
      // let obj = {
      //   name: "三蹦子",
      //   content: this.val,
      //   time: now,
      //   isME: 1,
      // };
      // this.list.push(obj);
      // this.val = "";
      // this.scrollToBottom();

      let obj = {
        name: "me",
        msg: this.val,
      };
      //
      const { topic, qos, payload } = this.publish;
      this.client.publish(topic, JSON.stringify(obj), qos, (error) => {
        if (error) {
          console.log("Publish error", error);
        }
      });
      this.val = "";
    },
    scrollToBottom() {
      var div = this.$refs.box;
      this.$nextTick(() => {
        div.scrollTop = div.scrollHeight;
      });
    },
    getNowTime(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },

     /** 机器人按钮操作 */
    feifei() {
      this.robotvisible = true;

    },


  }
};
</script>
<style lang="less" scoped>

.msgs {
  height: 400px;
  background-color: rgb(249, 251, 252);
  overflow-y: auto;
  padding: 5px;
}
.msgs li {
  margin-bottom: 15px;
}
.msgs small {
  font-size: 12px;
  color: #ccc;
  margin-top: 4px;
}
.msg-box {
  display: inline-block;
  padding: 10px;
  max-width: 48%;
}
.msg-box .title {
  font-size: 12px;
  margin-bottom: 4px;
}
.msg-box p {
  font-size: 14px;
  line-height: 1.5;
}
.msgs small {
  display: block;
}
/* 左边 */
.msg-l {
  text-align: left;
}
.msg-l .title {
  color: #ccc;
}
.msg-l p {
  color: #333;
}
.msg-l .msg-box {
  border-radius: 0 10px 10px 10px;
  background-color: rgb(234, 235, 241);
  position: relative;
  padding-left: 14px;
}
.msg-l .msg-box::before {
  content: "";
  width: 4px;
  height: calc(100% - 8px);
  position: absolute;
  left: 0;
  top: 0;
  background-color: rgb(11, 163, 133);
}
/* 右边 */
.msg-r {
  text-align: right;
}
.msg-r .title {
  color: rgb(156, 226, 194);
}
.msg-r p {
  color: #fff;
}
.msg-r .msg-box {
  background-color: rgb(56, 195, 139);
  border-radius: 10px 0 10px 10px;
}

.send-msg {
  height: 120px;
  background-color: #fff;
  border: 1px solid #ccc;
  position: relative;
}
.send-msg textarea {
  resize: none;
  width: 95%;
  height: 100px;
  /* padding: 10px 20px; */
  margin: 15px;
  border: 0;
  outline: none;
}
.el-icon-position {
  color: rgb(56, 195, 139);
  font-size: 24px;
  font-weight: 700;
  position: absolute;
  right: 20px;
  bottom: 25px;
  cursor: pointer;
}


</style>